package com.outsourcing.bottle.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.outsourcing.bottle.domain.StickEntry;
/**
 * 贴纸详情
 * @author ting
 *
 */
public class StickersTable {

	private final String TABLE_STICK_LIST = "stick_list";
	private static final String DIR_ID = "pasterdir_id";
	private static final String PASTER_ID = "paster_id";
	private static final String PASTER_URL= "paster_url";
	private DBManagerImpl db = null;
	public StickersTable() {
		if (db == null) {
			db = DBManager.get();
		}
		if (!db.isTableExits(db.getConnection(), TABLE_STICK_LIST)) {
			createStickers();
		}
	}
	
	private void createStickers() {
		String createSql = "create table if not exists "+TABLE_STICK_LIST+" (id integer primary key autoincrement, "+DIR_ID+" integer, "+PASTER_ID+" integer,"+PASTER_URL+" varchar)";
		db.creatTable(db.getConnection(), createSql, TABLE_STICK_LIST);
	}
	
	public ArrayList<StickEntry> getStickList(int dirId) {
		Cursor cursor = null;
		ArrayList<StickEntry> stickList = null;
		try {
			cursor = db.find(db.getConnection(), "select * from " + TABLE_STICK_LIST +" where "+DIR_ID+"=?", 
					new String[] { String.valueOf(dirId)});
			if (cursor != null) {
				stickList = new ArrayList<StickEntry>();
				while (cursor.moveToNext()) {
					StickEntry stickEntry = new StickEntry();
					stickEntry.setPaster_id(cursor.getInt(cursor.getColumnIndex(PASTER_ID)));
					stickEntry.setPaster_url(cursor.getString(cursor.getColumnIndex(PASTER_URL)));
					stickList.add(stickEntry);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return stickList;
	}
	
	public void saveStickList(int dirId,StickEntry stickEntry) {
		ContentValues values = new ContentValues();
		values.put(DIR_ID, dirId);
		values.put(PASTER_ID, stickEntry.getPaster_id());
		values.put(PASTER_URL, stickEntry.getPaster_url());
		db.save(db.getConnection(), TABLE_STICK_LIST, values);
	}
	
	public void clearTalbe() {
		db.delete(db.getConnection(), TABLE_STICK_LIST, null, null);
	}
}
